<template>
    <div>
        <div class="page-title">编辑信息</div>
        <el-form ref="form" :model="form" label-width="100px">
            <el-form-item label="分类.">
                <el-radio v-model="form.type" label="1">租房</el-radio>
                <el-radio v-model="form.type" label="2">二手房</el-radio>
            </el-form-item>

            <el-form-item label="标题.">
                <el-input ref="title" v-model="form.title" placeholder="请输入标题"></el-input>
            </el-form-item>

            <el-form-item label="封面图片.">
                <el-upload :action="uploadImage" :show-file-list="false" :before-upload="beforeUpload"
                    :on-success="uploadSuccess">
                    <div v-if="cover" class="relative">
                        <img :src="cover" class="banner">
                        <el-button class="reupload" icon="el-icon-refresh" size="mini">重新上传</el-button>
                    </div>
                    <i v-else class="el-icon-plus"></i>
                    <template #tip>
                        <div class="el-upload__tip">
                            只能上传 PNG / JPG / GIF / BMP / WEBP 文件，且不超过 2MB，建议尺寸 750 * 375
                        </div>
                    </template>
                </el-upload>
            </el-form-item>

            <el-form-item label="展示照片.">
                <div class="imageList" v-for="(item, index) in covers" :key='index'>
                    <img :src="item">
                    <i class="remove" @click="removeImage(index)">x</i>
                </div>
                <el-upload :action="uploadImage" :show-file-list="false" :on-success="uploadMultiSuccess"
                    :before-upload="beforeUpload">
                    <span class="warp">
                        <i class="el-icon-plus"></i>
                    </span>
                    <template #tip>
                        <div class="el-upload__tip">
                            只能上传 PNG / JPG / GIF / BMP / WEBP 文件，且不超过 2MB，建议尺寸 750 * 375
                        </div>
                    </template>
                </el-upload>
            </el-form-item>

            <el-form-item label="价格.">
                <el-input ref="price" v-model="form.price" placeholder="请输入价格" type="number">
                    <template #prepend>￥</template>
                </el-input>
            </el-form-item>

            <el-form-item label="房型.">
                <el-input ref="style" v-model="form.style" placeholder="请输入房型，例如：`两室一厅一卫`"></el-input>
            </el-form-item>

            <el-form-item label="面积.">
                <el-input ref="area" v-model="form.area" placeholder="请输入面积" type="number">
                    <template #append>㎡</template>
                </el-input>
            </el-form-item>

            <el-form-item label="楼层.">
                <el-input ref="floor" v-model="form.floor" placeholder="请输入楼层，例如：`6号楼15层`"></el-input>
            </el-form-item>

            <el-form-item label="朝向.">
                <el-radio v-model="form.direction" label="1">南北朝向</el-radio>
                <el-radio v-model="form.direction" label="2">东西朝向</el-radio>
            </el-form-item>

            <el-form-item label="标签.">
                <el-input ref="sign" v-model="form.sign" placeholder="请输入标签，请使用英文`,`分隔关键词"></el-input>
            </el-form-item>

            <el-form-item label="联系方式.">
                <el-input ref="tel" v-model="form.tel" placeholder="请输入联系方式"></el-input>
            </el-form-item>

            <el-form-item label="地址.">
                <el-input ref="address" v-model="form.address" placeholder="请输入地址"></el-input>
            </el-form-item>

            <el-form-item label="地图定位.">
                <div id="map"></div>
            </el-form-item>

            <el-form-item label="详情内容.">
                <Editor :value="editorValue" @change="changeEditor"></Editor>
            </el-form-item>

            <el-form-item label="排序.">
                <el-input ref="sort" v-model="form.sort" placeholder="请输入排序，（ 非必填，默认为0 ）"></el-input>
            </el-form-item>

            <el-form-item label="状态.">
                <el-switch v-model="form.status" active-color="#f8c15c"></el-switch>
            </el-form-item>

            <el-form-item>
                <el-button type="success" icon="el-icon-check" @click="submit">修改</el-button>
                <el-button icon="el-icon-close" @click="cancel">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
    import {
        get,
        put
    } from '@/network/request'
    import Editor from '@/components/Editor'
    import {
        __URL__
    } from '@/main'

    export default {
        name: 'EditTenancy',
        components: {
            Editor
        },
        data() {
            return {
                uploadImage: __URL__ + '/uploadImage', // 上传图片地址
                form: {
                    id: this.$route.params.id,
                    cid: sessionStorage.getItem('cid'),
                    type: '1',
                    title: '',
                    cover: '',
                    covers: '',
                    price: 0,
                    style: '',
                    area: '',
                    floor: '',
                    direction: '1',
                    sign: '',
                    tel: '',
                    address: '',
                    map: '',
                    content: '',
                    sort: '',
                    status: false
                },
                cover: '', // 封面
                covers: [], // 照片数组
                editorValue: '', // 富文本内容
                lat: '37.800578', // 纬度
                lng: '112.599885' // 经度
            }
        },
        mounted() {
            this.$nextTick(() => {
                // 获取信息
                get('/getTenancy', {
                    id: this.$route.params.id,
                    cid: sessionStorage.getItem('cid')
                }).then(res => {
                    const result = res.data
                    if (result.code == 200) {
                        this.form.type = result.data.type.toString()
                        this.form.title = result.data.title
                        this.form.cover = result.data.cover
                        this.form.price = result.data.price
                        this.form.style = result.data.style
                        this.form.area = result.data.area
                        this.form.floor = result.data.floor
                        this.form.direction = result.data.direction.toString()
                        this.form.sign = result.data.sign
                        this.form.tel = result.data.tel
                        this.form.address = result.data.address
                        this.form.map = result.data.map
                        this.form.sort = result.data.sort
                        this.form.status = (result.data.status == 1) ? true : false
                        this.editorValue = result.data.content
                        this.cover = result.data.cover
                        if (result.data.covers != '') this.covers = result.data.covers.split(',')

                        const arr = this.form.map.split(',')
                        this.lat = arr[0]
                        this.lng = arr[1]
                        this.map(this.lat, this.lng, 'show')
                    } else {
                        this.$router.push('/404')
                    }
                }).catch()
            })
        },
        methods: {
            // 地图
            map(lat, lng, type) {
                // 初始化地图
                let marker = null
                const center = new window.TMap.LatLng(lat, lng)
                const map = new window.TMap.Map(document.getElementById('map'), {
                    center: center, // 地图中心点坐标
                    zoom: 14, // 缩放级别
                    pitch: 45, // 俯仰角
                })
                if (type == 'show') {
                    if (!marker) {
                        marker = new window.TMap.MultiMarker({
                            map: map,
                            geometries: [{
                                position: center
                            }]
                        })
                    }
                }

                // 获取点击坐标，添加地图标记
                map.on('click', e => {
                    // 获取坐标
                    this.form.map = e.latLng.getLat().toFixed(6) + ',' + e.latLng
                        .getLng().toFixed(6)

                    // 取消标记
                    if (marker) {
                        marker.setMap(null)
                        marker = null
                    }

                    // 添加标记
                    if (!marker) {
                        marker = new window.TMap.MultiMarker({
                            map: map,
                            geometries: [{
                                position: e.latLng
                            }]
                        })
                    }
                })
            },
            // 富文本内容
            changeEditor(val) {
                this.form.content = val
            },
            // 上传准备
            beforeUpload(file) {
                if (['image/png', 'image/jpeg', 'image/gif', 'image/bmp', 'image/webp'].indexOf(file
                        .type) == -1) {
                    this.$message.error({
                        message: '请上传正确的图片格式！',
                        type: 'error',
                        offset: 70
                    })
                    return false
                }

                const size = file.size / 1024 / 1024 < 2
                if (!size) {
                    this.$message.error({
                        message: '图片大小不能超过 2MB！',
                        type: 'error',
                        offset: 70
                    })
                    return false
                }
            },
            // 上传成功
            uploadSuccess(res, file) {
                this.form.cover = res.data
                this.cover = URL.createObjectURL(file.raw)
            },
            // 上传成功(多图)
            uploadMultiSuccess(res) {
                this.covers.push(res.data)
            },
            // 移除图片(多图)
            removeImage(index) {
                this.covers.splice(index, 1)
            },
            // 提交
            submit() {
                if (this.form.title == '') {
                    this.$notify.info({
                        title: '系统提示',
                        message: '请输入标题',
                        offset: 70
                    })
                    this.$refs['title'].focus()
                    return false
                }

                if (this.form.cover == '') {
                    this.$notify.info({
                        title: '系统提示',
                        message: '请上传封面照片',
                        offset: 70
                    })
                    return false
                }

                if (this.form.price == 0) {
                    this.$notify.info({
                        title: '系统提示',
                        message: '请输入价格',
                        offset: 70
                    })
                    this.$refs['price'].focus()
                    return false
                }

                if (this.form.style == 0) {
                    this.$notify.info({
                        title: '系统提示',
                        message: '请输入房型',
                        offset: 70
                    })
                    this.$refs['style'].focus()
                    return false
                }

                if (this.form.area == 0) {
                    this.$notify.info({
                        title: '系统提示',
                        message: '请输入面积',
                        offset: 70
                    })
                    this.$refs['area'].focus()
                    return false
                }

                if (this.form.floor == 0) {
                    this.$notify.info({
                        title: '系统提示',
                        message: '请输入楼层',
                        offset: 70
                    })
                    this.$refs['floor'].focus()
                    return false
                }

                if (this.form.sign == 0) {
                    this.$notify.info({
                        title: '系统提示',
                        message: '请输入标签',
                        offset: 70
                    })
                    this.$refs['sign'].focus()
                    return false
                }

                if (this.form.tel == '') {
                    this.$notify.info({
                        title: '系统提示',
                        message: '请输入联系方式',
                        offset: 70
                    })
                    this.$refs['tel'].focus()
                    return false
                }

                if (this.form.address == '') {
                    this.$notify.info({
                        title: '系统提示',
                        message: '请输入地址',
                        offset: 70
                    })
                    this.$refs['address'].focus()
                    return false
                }

                if (this.form.map == '') {
                    this.$notify.info({
                        title: '系统提示',
                        message: '请在地图上选择地点',
                        offset: 70
                    })
                    return false
                }

                if (this.form.content == '') {
                    this.$notify.info({
                        title: '系统提示',
                        message: '请输入内容详情',
                        offset: 70
                    })
                    return false
                }

                this.form.covers = this.covers.toString()
                put('/modifyTenancy', this.form).then(res => {
                    const result = res.data
                    if (result.code == 200) {
                        this.$notify.success({
                            title: '系统提示',
                            message: '信息修改成功',
                            offset: 70
                        })
                        this.$router.push('/tenancy')
                    }
                }).catch()
            },
            // 取消
            cancel() {
                this.$router.push('/tenancy')
            }
        }
    }
</script>

<style>
</style>